package com.hjw.service.impl;

import com.hjw.dao.LargeFileDao;
import com.hjw.entity.LargeFile;
import com.hjw.service.LargeFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @创建时间：2025-04-14
 * @文件名称：satoken_sobuk - com.hjw.service.impl
 */
@Slf4j
@Service
public class LargeFileServiceImpl implements LargeFileService {

    @Autowired
    private LargeFileDao largeFileDao;
    @Autowired
    private RedisTemplate<String, LargeFile> redisTemplate;

    @Override
    public List<LargeFile> findAll() {
        return largeFileDao.findAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public int add(LargeFile largefile) {
        // 前置删除缓存
        redisTemplate.delete("largefile:"+largefile.getId());
        // 添加数据库
        int add = largeFileDao.add(largefile);
        // 后置删除缓存
        redisTemplate.delete("largefile:"+largefile.getId());
        return add;
    }

    @Override
    public LargeFile findOne(String id) {
        LargeFile l = redisTemplate.opsForValue().get("largefile:"+id);
        if (l == null){
            l = largeFileDao.findOne(id);
            if (l != null){
                redisTemplate.opsForValue().set("largefile:"+id,l,7200, TimeUnit.SECONDS);
            }
        }
        return l;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public int delete(String id) {
        redisTemplate.delete("largefile:"+id);
        int delete = largeFileDao.delete(id);
        if (delete == 0){
            throw new RuntimeException("删除失败");
        }
        redisTemplate.delete("largefile:"+id);
        return delete;
    }
}
